use std::time::Duration;

use async_trait::async_trait;
use base_data::channel::EndReason;
use tokio::time::sleep;
use tools::{utils::gen_id::get_now_duration, ResultNull};
use tracing::info;

use crate::{
	business::{
		bus_trait::Business,
		inbound400::context::{BusinessState, InboundRunContext},
	},
	link_to_sip::{answer, play_sound_file_to_caller},
};

///用户设置节点拒接，此功能只循环放单，但不呼叫后续节点
#[derive(Debug, Clone)]
pub struct NodeTimeRefuse;

#[async_trait]
impl Business for NodeTimeRefuse {
	type C = InboundRunContext;

	async fn check(&self, context: &mut Self::C) -> ResultNull {
		if get_now_duration().as_secs() > context.check_time.as_secs() + 80 {
			context.business_state = BusinessState::End(EndReason::NoAllowTimeCaller);
		}
		Ok(())
	}

	async fn hangup(
		&self,
		context: &mut Self::C,
		_channel_id: u32,
		_reason: EndReason
	) -> ResultNull {
				info!("节点时段限制放音中,收到挂断消息");
		context.business_state = BusinessState::End(EndReason::NoAllowTimeCaller);

		Ok(())
	}

	async fn play_back_stop(&self, context: &mut Self::C,_channel_id:u32) -> ResultNull {
		// //这里播放完成以后，继续播放
		// play_bell(
		// 	handler.get_tx(),
		// 	&context.caller_uuid,
		// 	&self.node_info.conn_begin_bell_path,
		// )
		// .await?;

		if !context.is_answered_caller() {
			//试一下播放完立即接通
			answer(context.caller_channel())?;
		}

		sleep(Duration::from_secs(1)).await;
		//有了接通信号立即退出
		context.business_state = BusinessState::End(EndReason::NoAllowTimeCaller);

		Ok(())
	}

	async fn start_call(&self, context: &mut Self::C) -> ResultNull {
		if !context.is_answered_caller() && context.node_info.immconnect {
			context.start_charge();
			answer(context.caller_channel())?;
		}

		play_sound_file_to_caller(
			context.caller_channel(),
			&context.node_info.conn_begin_bell_path,
		)?;

		Ok(())
	}
}